package com.xxkj.drugtraceability.ui.doctoradvicecollection

import android.app.Application
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.net.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: zhoujingjin
 * created on: 2024/9/10 16:15
 * description:
 */
class DoctorAdviceCollectionViewModel(application: Application, private val repository: DoctorAdviceCollectionRepository):BaseViewModel(application) {
    var prescriptioninfo = MutableLiveData<List<DoctorAdviceInfoBean>?>()
    var showList = mutableListOf<DrugInfoBean>()
    var baseUiModel = MutableLiveData<BaseUiModel<Boolean>>()
    //是否可以扫溯源码，如果处方码已经保存过追溯码，无论保存的多少，都不再让保存了。
    var canAdd = true
    var selectIndex = MutableLiveData(-1)
    var lastIndex = -1
    var barcode = ""
    var Prescriptionbarcode = ""
//    var rxno = ""
    var uiState = MutableLiveData<UiState<String>>()
    var usedCount: String = "0"
    var trugTracCodgIsGatherData:DrugDictDataList? = null
    /**
     * 获取病人某个时间的医嘱列表
     */
    fun getDoctorOrderedInfoList(date:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                val start = System.currentTimeMillis()
                uiState.postValue(UiState(isLoading = true))
                val result = repository.getDoctorOrderedInfoList(date)
                if (result is Result.Success){
                    val spend = System.currentTimeMillis()-start
                    Log.e("耗时",spend.toString()+"ms")
                    //获取成功了
                    var index = 0
                    showList.clear()
                    result.data.data.forEach {
                        it.dataForm = "02"
                        it.drugInfoList?.let {list->
                            list.forEach { druginfo->
                                druginfo.index = index
                                druginfo.takeDrug = it.takeDrug
                                druginfo.presType = it.presType
                                index++
                            }
                            showList.addAll(list)
                        }
//                        it.drugInfoList?.forEach { druginfo->
//                            druginfo.takeDrug = it.takeDrug
//                            druginfo.presType = it.presType
//                        }
//                        showList.addAll(it.drugInfoList)
                    }
                    prescriptioninfo.postValue(result.data.data)
                    uiState.postValue(UiState(isLoading = false))
                }else if (result is Result.Error){
                    uiState.postValue(UiState(isLoading = false,isError = result.errorData?:result.exception.message))
                }
            }}
    }
    fun trugTracCodgIsGather(barcode:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                this@DoctorAdviceCollectionViewModel.barcode = barcode
                val result = repository.trugTracCodgIsGather(Gson().toJson(TraceRequest(barcode,"2")))
                try {
                    if (result is Result.Success){
                        if (result.data.data.isGather){
                            if (!result.data.data.isCheckUsedCount.isNullOrEmpty()&&"1"==result.data.data.isCheckUsedCount) {
                                if (!result.data.data.usedCount.isNullOrEmpty()) {
                                    usedCount = result.data.data.usedCount
                                }
                            }
                            if(result.data.data.drugDictInfo==null){
                                baseUiModel.postValue(BaseUiModel(showLoading = false,showError = "未找到与溯源码匹配的药品,请手动选中到待扫描的药品"))
                            }
                            else{
                                trugTracCodgIsGatherData = result.data.data
                                var indexTemp = -1
                                if (showList.isNotEmpty()){
                                    run loop@{
                                        showList.forEachIndexed { index, drugInfoBean ->
                                            try {
                                                result.data.data.drugDictInfo.forEach { resultDrugDictInfo ->
                                                    if (resultDrugDictInfo.drugCode == drugInfoBean.drugCode &&
                                                        !drugInfoBean.trugTracCodgIsGatherCount) {
                                                        indexTemp = index
                                                        lastIndex = selectIndex.value ?: -1
                                                        selectIndex.postValue(index)
                                                        return@loop
                                                    }
                                                }
                                            } catch (e: Exception) {
                                            }
                                        }
                                    }

                                    }
                                //选中的时候就算没有查到也要去往里面加
                                if (selectIndex.value != -1) {
                                    var temp = showList[selectIndex.value!!]
                                    if (!temp!!.trugTracCodgIsGatherCount) {
                                        selectIndex.postValue(selectIndex.value)
                                    }
                                    baseUiModel.postValue(BaseUiModel(showLoading = false))
                                } else {
                                    if (indexTemp == -1) {
                                        baseUiModel.postValue(
                                            BaseUiModel(
                                                showLoading = false,
                                                showError = "未找到与溯源码匹配的药品,请手动选中到待扫描的药品"
                                            )
                                        )
                                    } else {
                                        baseUiModel.postValue(BaseUiModel(showLoading = false))
                                    }
                                }

                            }
                        }else{
                            baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.data.data.gatherMsg))
                        }

                    }else if (result is Result.Error){
                        baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                    }
                } catch (e: Exception) {
                }
            }
        }
    }

    /**
     * 保存数据
     */
    fun finishScanDrugCode(finishRequest: FinishAdviceRequest){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                val result = repository.finishScanDrugCode(GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(finishRequest))
                if (result is Result.Success){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showSuccess = true))
                    barcode = ""
                    prescriptioninfo.postValue(mutableListOf())
                    Prescriptionbarcode = ""
                    showList = mutableListOf()
                    lastIndex = -1
                    canAdd = false
                    usedCount = "0"
                    trugTracCodgIsGatherData=null
                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }
}